<script setup>
import { computed, onBeforeUnmount, defineEmits, ref } from 'vue'
import { Editor, Toolbar, getEditor, removeEditor } from '@wangeditor/editor-for-vue'
import cloneDeep from 'lodash.clonedeep'
import { uploadFile } from '@utils/obs.js'

// import { DomEditor } from '@wangeditor/editor'

const props = defineProps({
  defaultContent: {
    type: String,
    default: '[]'
  },
  height: {
    type: String,
    default: '500px'
  },
  type: {
    type: String,
    default: null
  },
  //摘要长度
  textNum: {
    type: Number,
    default: 30
  },
  //唯一id标识
  keyId: {
    type: String
  },
  //工具栏数组
  excludeKeys: {
    type: String
  }
})

const emit = defineEmits(['content-change'])

const fullscreenLoading = ref(false)

// 定义一个编辑器 id ，要求：全局唯一且不变！！！
const editorId = props.keyId || 'editor-id'

// 编辑将默认显示的内容
const getDefaultContent = computed(() => {
  const arr = JSON.parse(props.defaultContent)
  return cloneDeep(arr)
}) // 注意，深拷贝

// 工具栏配置
const toolbarConfig = {
  excludeKeys: props.excludeKeys ? props.excludeKeys.split(',') : ['insertImage', 'insertVideo', 'insertLink', 'emotion', 'todo']
}

// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      customUpload(file, insertFn) {
        fullscreenLoading.value = true
        uploadFile({ file })
          .then((res) => {
            insertFn(res.url)
          })
          .finally(() => {
            fullscreenLoading.value = false
          })
      }
    },
    uploadVideo: {
      customUpload(file, insertFn) {
        fullscreenLoading.value = true
        uploadFile({ file })
          .then((res) => {
            let url = res.url
            if (res.url.indexOf('http') < 0) {
              url = `http://${res.url}`
            }
            insertFn(url)
          })
          .finally(() => {
            fullscreenLoading.value = false
          })
      }
    }
  }
}

// 回调函数
const handleChange = (editor) => {
  // console.log('change:', JSON.stringify(editor.children))
  // console.log(editor.getHtml())
  // console.log('text', editor.getText())
  // 获取摘要信息
  const text = editor.getText().replace(/\n/g, '').trim().replace(/ /g, '').substring(0, props.textNum)
  emit('content-change', JSON.stringify(editor.children), editor.getHtml(), text, props.type)
  // const toolbar = DomEditor.getToolbar(getEditor(editorId))
  // console.log(toolbar)
}

// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = getEditor(editorId)
  if (editor == null) return

  // 销毁，并移除 editor
  editor.destroy()
  removeEditor(editorId)
})
</script>

<template>
  <div style="border: 1px solid #ccc; width: 100%" v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="上传中...">
    <!-- 工具栏 -->
    <Toolbar :editorId="editorId" :defaultConfig="toolbarConfig" style="border-bottom: 1px solid #ccc" />
    <!-- 编辑器 -->
    <Editor :editorId="editorId" :defaultConfig="editorConfig" :defaultContent="getDefaultContent" @onChange="handleChange" :style="'height: ' + height" />
  </div>
</template>

<!-- 别忘了引入样式 -->
<style src="@wangeditor/editor/dist/css/style.css"></style>
